package com.nitobi.flexunit.junit
{
	import flash.desktop.NativeApplication;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	
	import flexunit.framework.AssertionFailedError;
	import flexunit.framework.Test;
	
	public class JUnitTestRunnerAIR extends JUnitTestRunner
	{
		
		private var outputDir:File;
		private var errorCount:uint = 0;
    	private var failureCount:uint = 0;
		
		public function JUnitTestRunnerAIR()
		{
			super();
		}
		
		/**
		 * 
		 * @param test
		 * @param outputDir
		 * 
		 * starts the init test and is the initial function
		 */		
		public function start(test:Test, outputDir:File):void
    	{
    		if(outputDir != null && outputDir.isDirectory)
    		{
    			this.outputDir = outputDir;
		   		super.run(test);
		   	}
		   	else
		   	{
		   		throw new Error("Invalid output directory: " + outputDir);
		   	}
    	}
		
		/**
		 * 
		 * @param test
		 * @param error
		 * 
		 * overwritten so we can count the failures
		 */		
		override public function addFailure(test:Test, error:AssertionFailedError):void
		{
			super.addFailure(test, error);
			++failureCount;
		}
		
		/**
		 * 
		 * @param test
		 * @param error
		 * 
		 * overwritten so we can count the errors
		 */		
		override public function addError(test:Test, error:Error):void
		{
			super.addError(test, error);
			++errorCount;
		}
		
		/**
		 * 
		 * @param test
		 * 
		 * overwritten since we do not want to send the result via XMLSocket
		 * but with the AIR File API
		 */		
		override public function endTest(test:Test):void
		{	
			if(++numTestsRun == totalTestCount)
			{
				handleResult();
   			}
		}
		
		/**
		 * write the results in the output directory
		 * specified in the start method
		 */		
		private function handleResult():void
		{
			// counter for the test result filenames so you see the order in
			// which they were executed
			var i:uint = 0;
			
			for(var className:String in reports)
			{
				var xml:XML = createXMLReport(reports[className]);
				var xmlResult : String = '<?xml version="1.0" encoding="UTF-8"?>\n' + xml.toString();
				var outputFile:File = outputDir.resolvePath(i++ + "_TEST-" + xml.@name + ".xml");
				var fs:FileStream = new FileStream();
				fs.open(outputFile, FileMode.WRITE);
				fs.writeUTFBytes(xmlResult);
				fs.close();
			}
			
			var exitCode:int = errorCount > 0 || failureCount > 0 ? 1 : 0;
			trace("test successfull:", exitCode == 0);
			NativeApplication.nativeApplication.exit(exitCode);
		}
		
	}
}